package com.hencoder.hencoderpracticedraw1.practice;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;


/*
 *  @创建者:   Yio
 *  @创建时间:  2017/11/23 16:56
 *  @描述：    饼图
 */

public class PieChartView extends View {

    private Paint paint;
    private float repayment;
    private float principalSum;
    private float raduis;//半径
    private float total=0;
    private RectF oval;
    private float margin;//间隔宽度

    public PieChartView(Context context) {
        this(context, null);
    }

    public PieChartView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        raduis = 81;
        margin = 6;

        oval = new RectF(-raduis, -raduis, raduis, raduis);
    }

    public void setPieChartData(float repayment, float principalSum) {
        this.repayment = 610;
        this.principalSum = 1309;
        total = this.repayment + this.principalSum;

        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(200, 200);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (total != 0) {
            int centerX = getWidth() / 2;
            int centerY = getHeight() / 2;
            //移动画布至view中心
            canvas.translate(centerX, centerY);

            float sweepAngle = repayment / total * 360.0f;
            paint.setColor(Color.parseColor("#ffd200"));
            float startAngle = -100.0f;
            //求组黄色弧线中心点坐标
            float angle = startAngle + sweepAngle / 2;
            float arcCenterX = raduis * (float) Math.cos(angle * Math.PI / 180.0f);
            float arcCenterY = raduis * (float) Math.sin(angle * Math.PI / 180.0f);
            canvas.save();
            float dx = Math.min(0, arcCenterX) > 0 ? -margin : margin;
            float dy = Math.min(0, arcCenterY) > 0 ? margin : -margin;
            canvas.translate(dx, dy);
            //画黄色区域
            canvas.drawArc(oval, startAngle, sweepAngle, true, paint);
            canvas.restore();
            //画粉色区域
            startAngle += sweepAngle;
            sweepAngle = principalSum / total * 360.0f;
            paint.setColor(Color.parseColor("#ff6c7f"));
            canvas.drawArc(oval, startAngle, sweepAngle, true, paint);
        }
    }
}
